﻿using FreeDream.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Profiling;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace FreeDream.WebApi.Controllers
{
    /// <summary>
    /// 测试使用
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AdvertisementController : ControllerBase
    {
        private readonly ILogger<AdvertisementController> _logger;

        public AdvertisementController(ILogger<AdvertisementController> logger)
        {
            _logger = logger;
        }

        // GET: api/<AdvertisementController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        /// <summary>
        /// 产生不重复随机数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET api/<AdvertisementController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            #region 产生不重复随机数

            int[] intArray = new int[100];
            List<int> newArray = new List<int>();
            Random rnd = new Random();
            while (newArray.Count < 100)
            {
                int tempNumber = rnd.Next(1, 101);
                if (!newArray.Contains(tempNumber))
                    newArray.Add(tempNumber);
            }
            newArray.Sort();

            #endregion

            return "value";
        }

        // POST api/<AdvertisementController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/<AdvertisementController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<AdvertisementController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }


        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        [HttpGet("token")]
        public async Task<IActionResult> GetJwtStr()
        {
            using (MiniProfiler.Current.Step("获取成功后，开始处理最终数据"))
            {
            }

            // 将用户id和角色名，作为单独的自定义变量封装进 token 字符串中。
            TokenModelJwt tokenModel = new TokenModelJwt { Uid = 1, Role = "Admin" };
            var jwtStr = JwtTokenHelper.IssueJwt(tokenModel);//登录，获取到一定规则的 Token 令牌
            var suc = true;
            return Ok(new
            {
                success = suc,
                token = jwtStr
            });
        }

        /// <summary>
        /// 创建Token
        /// </summary>
        /// <returns></returns>
        [HttpGet("CreateToken")]
        public string CreateToken()
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
                new Claim("Id", "9527"),
                new Claim("Name", "Admin")
            };

            // 2. 从 appsettings.json 中读取SecretKey
            //var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecretKey:sdfsdfsrty45634kkhllghtdgdfss345t678fs"));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 从 appsettings.json 中读取Expires
            //var expires = Convert.ToDouble(_configuration["JWT:Expires"]);
            var expires = Convert.ToDouble("3");

            // 6. 根据以上，生成token
            //var token = new JwtSecurityToken(
            //    _configuration["JWT:Issuer"],     //Issuer
            //    _configuration["JWT:Audience"],   //Audience
            //    claims,                          //Claims,
            //    DateTime.Now,                    //notBefore
            //    DateTime.Now.AddDays(expires),   //expires
            //    signingCredentials               //Credentials
            //);
            var token = new JwtSecurityToken(
                "Issuer",     //Issuer
                "Audience",   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddDays(expires),   //expires
                signingCredentials               //Credentials
            );

            // 7. 将token变为string
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return jwtToken;


            #region 在Program.cs中，将JWT添加到服务中 --安装Microsoft.AspNetCore.Authentication.JwtBearer

            //builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            //{
            //    options.TokenValidationParameters = new TokenValidationParameters()
            //    {
            //        ValidateIssuer = true,
            //        ValidIssuer = builder.Configuration["JWT:Issuer"],
            //        ValidateAudience = true,
            //        ValidAudience = builder.Configuration["JWT:Audience"],
            //        ValidateLifetime = true,
            //        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"]))
            //    };
            //});

            //app.UseAuthentication();
            //app.UseAuthorization();

            #endregion
        }

    }
}
